package br.ufrj.dcc.smarthotel;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Util {

	private static Util myInstance;
	private Context context;
	
	private Util (Context context){
		myInstance = this;
		this.context = context; 
	}
	
	public static Util getInstance(Context context){
		if (myInstance == null) {
			myInstance = new Util(context);
		}
		return myInstance;
	}
	
	public String writeDate(Date date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		
		return dateFormat.format(date);
	}
	
	public String writeDateTime(Date date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
		
		return String.format(this.context.getString(R.string.conf_DateTime), dateFormat.format(date), timeFormat.format(date));
	}
	
	public InputStream downloadFile(String fileUrl) {
		URL myFileUrl = null;
		InputStream filestream = null;
		try {
			myFileUrl = new URL (fileUrl);
			HttpURLConnection connection = (HttpURLConnection) myFileUrl.openConnection();
			connection.setDoInput(true);
			connection.connect();
			filestream = connection.getInputStream();
		} catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
      }
		return filestream;
	}
	
    public Bitmap downloadImage(String fileUrl){
    	InputStream fileStream = this.downloadFile(fileUrl);
    	Bitmap image = null;
    	if (fileStream != null) {
    		image =  BitmapFactory.decodeStream(fileStream);
    	}
    	return image;
     }

    public JSONObject serverHttpGetObject(String url, List<BasicNameValuePair> params) {
		JSONObject result = null;
		try {
			result = new JSONObject(this.serverHttpGet(this.urlBuilder(url,params)));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
    
    
	public JSONObject[] serverHttpGetList(String url, List<BasicNameValuePair> params) {
		String result = this.serverHttpGet(this.urlBuilder(url,params));
		JSONObject[] resultArray = null;
		
		try {
			JSONArray jsonResult = new JSONArray(result);
			resultArray = this.convertJSONArrayToJSONObjectArray(jsonResult);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultArray;

	}
	
	
	private String serverHttpGet(String url) {
		String result = null;
		HttpClient httpclient = new DefaultHttpClient();  
        HttpGet request = new HttpGet(url);
        //TODO Descobrir Id do Celular que esta enviando a requisicao
        request.addHeader("deviceId", "1");  
        ResponseHandler<String> handler = new BasicResponseHandler();  
        try {  
            result = httpclient.execute(request, handler);  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  finally {
        	httpclient.getConnectionManager().shutdown();
        }
        return result;
	}
	
	public String urlBuilder(String url, List<BasicNameValuePair> params) {
		if (params != null && params.size() > 0) {
			if(!url.endsWith("?")) {
		        url += "?";
			}
	
		    String paramString = URLEncodedUtils.format(params, "utf-8");
	
		    url += paramString;
		}
	    return url;

	}
	
	private JSONObject[] convertJSONArrayToJSONObjectArray(JSONArray jsonArray) {
		int length = jsonArray.length();
		JSONObject[] jsonObjectArray = new JSONObject[length];
		try {
			for (int i = 0; i < jsonArray.length(); i++) {
				jsonObjectArray[i] = jsonArray.getJSONObject(i);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObjectArray;
	}
	
	public String getFormatedLocation(JSONObject location) {
		String formatedLocation = "";
		
		try {
			formatedLocation = location.getDouble("lat") + "," + location.getDouble("lng");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return formatedLocation;
	}
}
